package org.dingyom.org.service.impl;

import org.dingyom.basics.constants.BaseConstants;
import org.dingyom.basics.constants.LogininfoConstants;
import org.dingyom.org.domain.Employee;
import org.dingyom.org.mapper.EmployeeMapper;
import org.dingyom.org.service.IEmployeeService;
import org.dingyom.basics.service.impl.BaseServiceImpl;
import org.dingyom.user.domain.Logininfo;
import org.dingyom.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dingyom
 * @since 2022-09-01
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    @Transactional
    public void add(Employee employee) {
        //loginInfo 也要保存
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        employee.setState(BaseConstants.Employee.STATE_NORMAL);
        logininfo.setType(LogininfoConstants.LOGININFO_TYPE_ADMIN);
        if (employee.getState() == BaseConstants.Employee.STATE_NORMAL){//员工状态是正常 登陆用户就是可用
            logininfo.setDisable(LogininfoConstants.LOGININFO_DISABLE_YES);
        }else {//员工状态不是1 那就是注销或被停用 登陆用户就不可用
            logininfo.setDisable(LogininfoConstants.LOGININFO_DISABLE_NO);
        }
        logininfoMapper.save(logininfo);

        //设置登陆用户的返回的自增id
        employee.setLogininfoId(logininfo.getId());
        employeeMapper.save(employee);
    }

    @Override
    @Transactional
    public void modify(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);//用beanUtils 工具类复制相同属性的值
        logininfo.setId(employee.getLogininfoId());//注意 这里logininfo的id要改 不是employee的id 而是getLogininfoId()
        logininfo.setType(LogininfoConstants.LOGININFO_TYPE_ADMIN);
        if (employee.getState()== BaseConstants.Employee.STATE_NORMAL){//员工状态是正常 登陆用户就是可用
            logininfo.setDisable(LogininfoConstants.LOGININFO_DISABLE_YES);
        }else {//员工状态不是1 那就是注销或被停用 登陆用户就不可用
            logininfo.setDisable(LogininfoConstants.LOGININFO_DISABLE_NO);
        }
        logininfoMapper.update(logininfo);

        employeeMapper.update(employee);
    }

    @Override
    @Transactional
    public void delete(Serializable id) {
        Employee employee = employeeMapper.loadById(id);
        Logininfo logininfo = new Logininfo();

        logininfo.setId(employee.getLogininfoId());
        logininfoMapper.remove(logininfo.getId());
        employeeMapper.remove(id);
    }
}
